import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Row,
  Col,
  Statistic,
  Typography,
  Drawer,
  Descriptions,
  Divider,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  FilterOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import {
  fetchProducts,
  fetchCategories,
  fetchProduct,
  searchProducts,
  setFilters,
  clearFilters,
} from '../store/slices/productSlice';
import MainLayout from '../components/Layout/MainLayout';
import ResizableTable from '../components/ResizableTable';
import { Product, RISK_LEVELS, PRODUCT_STATUS } from '../types';

const { Title, Text } = Typography;
const { Option } = Select;
const { Search } = Input;

const Products: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const {
    products,
    categories,
    loading,
    filters,
    pagination,
    currentProduct,
  } = useAppSelector((state: any) => state.product);
  
  const [detailVisible, setDetailVisible] = useState(false);
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    dispatch(fetchProducts({}));
    dispatch(fetchCategories());
  }, [dispatch]);

  const handleSearch = (value: string) => {
    setSearchValue(value);
    if (value.trim()) {
      dispatch(searchProducts(value.trim()));
    } else {
      dispatch(fetchProducts({}));
    }
  };

  const handleFilterChange = (key: string, value: any) => {
    dispatch(setFilters({ [key]: value }));
    dispatch(fetchProducts({ ...filters, [key]: value }));
  };

  const handleClearFilters = () => {
    dispatch(clearFilters());
    setSearchValue('');
    dispatch(fetchProducts({}));
  };

  const handleViewDetail = async (product: Product) => {
    await dispatch(fetchProduct(product.id));
    setDetailVisible(true);
  };

  const handleTableChange = (paginationInfo: any) => {
    dispatch(fetchProducts({
      ...filters,
      page: paginationInfo.current,
      page_size: paginationInfo.pageSize,
    }));
  };

  const columns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      render: (text: string, record: Product) => (
        <Button
          type="link"
          onClick={() => handleViewDetail(record)}
          style={{ padding: 0, textAlign: 'left' }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '产品代码',
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: '分类',
      dataIndex: 'category_name',
      key: 'category_name',
      width: 100,
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 100,
      render: (level: number) => (
        <Tag color={level <= 2 ? 'green' : level <= 3 ? 'orange' : 'red'}>
          {RISK_LEVELS[level as keyof typeof RISK_LEVELS]}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : status === 'suspended' ? 'orange' : 'red'}>
          {PRODUCT_STATUS[status as keyof typeof PRODUCT_STATUS]}
        </Tag>
      ),
    },
    {
      title: '最小投资额',
      dataIndex: 'min_investment',
      key: 'min_investment',
      width: 120,
      render: (value: number) => `¥${value ? value.toLocaleString() : '0'}`,
      sorter: true,
    },
    {
      title: '预期收益率',
      dataIndex: 'expected_return',
      key: 'expected_return',
      width: 120,
      render: (value: number) => `${value ? value.toFixed(2) : '0.00'}%`,
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: Product) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>产品管理</Title>
          <Text type="secondary">浏览和管理投资产品</Text>
        </div>

        {/* 统计概览 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="产品总数"
                value={pagination.total_count}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="活跃产品"
                value={products.filter((p: Product) => p.status === 'active').length}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="产品分类"
                value={categories.length}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                  title="平均管理费率"
                  value={products.length > 0 ? 
                    products.reduce((sum: number, p: Product) => sum + p.management_fee, 0) / products.length : 0
                  }
                  precision={2}
                  valueStyle={{ color: '#fa8c16' }}
                  suffix="%"
                />
            </Card>
          </Col>
        </Row>

        {/* 搜索和筛选 */}
        <Card style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={8}>
              <Search
                placeholder="搜索产品名称或代码"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                onSearch={handleSearch}
                enterButton={<SearchOutlined />}
                allowClear
              />
            </Col>
            <Col xs={24} sm={4}>
              <Select
                placeholder="产品分类"
                value={filters.category}
                onChange={(value) => handleFilterChange('category', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Array.isArray(categories) ? categories.map((category: any) => (
                  <Option key={category.id} value={category.id}>
                    {category.name}
                  </Option>
                )) : []}
              </Select>
            </Col>
            <Col xs={24} sm={4}>
              <Select
                placeholder="风险等级"
                value={filters.risk_level}
                onChange={(value) => handleFilterChange('risk_level', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.entries(RISK_LEVELS).map(([key, value]) => (
                  <Option key={key} value={parseInt(key)}>
                    {value}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={24} sm={4}>
              <Select
                placeholder="产品状态"
                value={filters.status}
                onChange={(value) => handleFilterChange('status', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.entries(PRODUCT_STATUS).map(([key, value]) => (
                  <Option key={key} value={key}>
                    {value}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={24} sm={4}>
              <Space>
                <Button
                  icon={<FilterOutlined />}
                  onClick={handleClearFilters}
                >
                  清除筛选
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() => dispatch(fetchProducts({}))}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 产品列表 */}
        <Card title="产品列表">
          <ResizableTable
            columns={columns}
            dataSource={Array.isArray(products) ? products : []}
            loading={loading}
            rowKey="id"
            pagination={{
              current: pagination.page,
              pageSize: pagination.page_size,
              total: pagination.total_count,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条产品`,
            }}
            onChange={handleTableChange}
            scroll={{ x: 1000 }}
          />
        </Card>

        {/* 产品详情抽屉 */}
        <Drawer
          title="产品详情"
          placement="right"
          width={600}
          open={detailVisible}
          onClose={() => setDetailVisible(false)}
        >
          {currentProduct && (
            <div>
              <Descriptions
                title={currentProduct.name}
                bordered
                column={1}
                size="small"
              >
                <Descriptions.Item label="产品代码">
                  {currentProduct.code}
                </Descriptions.Item>
                <Descriptions.Item label="产品分类">
                  {currentProduct.category?.name || '未分类'}
                </Descriptions.Item>
                <Descriptions.Item label="风险等级">
                  <Tag color={currentProduct.risk_level <= 2 ? 'green' : currentProduct.risk_level <= 3 ? 'orange' : 'red'}>
                    {RISK_LEVELS[currentProduct.risk_level as keyof typeof RISK_LEVELS]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="产品状态">
                  <Tag color={currentProduct.status === 'active' ? 'green' : currentProduct.status === 'suspended' ? 'orange' : 'red'}>
                    {PRODUCT_STATUS[currentProduct.status as keyof typeof PRODUCT_STATUS]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="最小投资额">
                  ¥{currentProduct.min_investment ? currentProduct.min_investment.toLocaleString() : '0'}
                </Descriptions.Item>
                <Descriptions.Item label="管理费率">
                  {currentProduct.management_fee ? Number(currentProduct.management_fee).toFixed(2) : '0.00'}%
                </Descriptions.Item>
                <Descriptions.Item label="产品类型">
                  {currentProduct.product_type}
                </Descriptions.Item>
              </Descriptions>
              
              <Divider />
              
              <div>
                <Title level={4}>产品描述</Title>
                <Text>{currentProduct.description || '暂无描述'}</Text>
              </div>
            </div>
          )}
        </Drawer>
      </div>
    </MainLayout>
  );
};

export default Products;